package info.empathymobile.forecast.util;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;

public class ComponentsInfo {
	//Power Profile for Galaxy S3 Mini
	//private static final double[] Freqs = { 200, 500, 800, 1000, 1200 }; // in MHz
	//private static final double[] PowerUsageForEachFreq = { 55, 148, 249, 408, 577 }; // in mA (Additional Power Use at that speed)
	
	//Power Profile for Galaxy S5
	private static final double[] Freqs = { 400 }; // in MHz
	private static final double[] PowerUsageForEachFreq = { 200 }; // in mA (Additional Power Use at that speed)
	
	public static double getCpuPowerUsageNow() {
		double cpuFreqNow = readCpuFreq();
		int FreqIndex = Arrays.binarySearch(Freqs, cpuFreqNow);
		double PowerUsageNow = PowerUsageForEachFreq[FreqIndex];
        
		return PowerUsageNow;
	}
	
	/*
	 * Returns the frequency of the processor in Mhz. If the frequency cannot be
	 * determined returns a negative value instead.
	 */
	private static double readCpuFreq() {
		/*
		 * Try to read from the /sys/devices file first. If that doesn't work
		 * try manually inspecting the /proc/cpuinfo file.
		 */
		long cpuFreqKhz = SystemInfo.getInstance().readLongFromFile(
				"/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq");
		if (cpuFreqKhz != -1) {
			return cpuFreqKhz / 1000.0;
		}

		FileReader fstream;
		try {
			fstream = new FileReader("/proc/cpuinfo");
		} catch (FileNotFoundException e) {
			System.out.println("Could not read cpu frequency file");
			return -1;
		}
		BufferedReader in = new BufferedReader(fstream, 500);
		String line;
		try {
			while ((line = in.readLine()) != null) {
				if (line.startsWith("BogoMIPS")) {
					return Double.parseDouble(line.trim().split("[ :]+")[1]);
				}
			}
		} catch (IOException e) {
			/* Failed to read from the cpu freq file. */
		} catch (NumberFormatException e) {
			/* Frequency not formatted properly as a double. */
		}
		System.out.println("Failed to read cpu frequency");
		return -1;
	}
	
	public static long getUsedMemory(){
		return Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
	}
}
